package controllers.api;

import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;

import controllers.BaseController;

import models.User;

import play.Logger;

public class TaskController extends BaseController {
	private static final String EMAIL_DOMAIN_SUFFIX = "@talkmefy.appspotmail.com";
	private static final String APP_DOMAIN_SUFFIX = "http://talkmefy.appspot.com/a/";
	
	public static void notificateByMail(String fromId, String dstId, String msgContent, String numberAttach, String residenceDomain) {
		User from = User.findById(Long.parseLong(fromId));
		User dst = User.findById(Long.parseLong(dstId));
		
		String fromName = from.basic_information.firstName + " " + from.basic_information.lastName;
		String dstName = dst.basic_information.firstName + " " + dst.basic_information.lastName;
		
		Logger.info("Sending email from: ", from);
		Logger.info("Sending email to: ", dst);
		
		StringBuilder subject = new StringBuilder();
		subject.append("Tienes un nuevo mensaje de: " + fromName);
		
		StringBuilder msgBody = new StringBuilder();
		msgBody.append("Hola ").append(dstName).append(",");
		msgBody.append("\n\n");
		msgBody.append(fromName).append(" te ha enviado un nuevo mensaje a Batzen con el siguiente texto: \n\n");
		msgBody.append("\t").append(msgContent).append("\n\n");
		if(Integer.parseInt(numberAttach) > 0) {
			msgBody.append("Además te ha compartido ").append(numberAttach).append(" elementos!");
		}
		msgBody.append("\n\n");
		msgBody.append("Entra con tu cuenta en Batzen pinchando en el siguiente enlace y respondele!").append("\n\n");
		
		StringBuilder accessUrl = new StringBuilder(APP_DOMAIN_SUFFIX).
				append(residenceDomain);
		
		msgBody.append(accessUrl);
		
		if(dst.basic_information.email == null) {
			Logger.warn("This user %s with id %d has not a email address, this notification will not be sent.", dstName, dst.id);
		} else {
			Properties props = new Properties();
			Session session = Session.getDefaultInstance(props, null);
			Message msg = new MimeMessage(session);
			try {
				msg.setFrom(new InternetAddress("notifications" + EMAIL_DOMAIN_SUFFIX));
				msg.addRecipient(Message.RecipientType.TO, new InternetAddress(dst.basic_information.email));
				msg.setSubject(subject.toString());
				msg.setText(msgBody.toString());
				Transport.send(msg);
			} catch (Exception e) {
				Logger.error(e.getMessage());
			}
		}
		
		ok();
	}

}
